<template>

  <!-- 使用 
  <NavBar 
  fixed控制顶部固定 
  :color控制字体颜色 
  leftIcon 控制左边返回是否显示
  @click-left="onLeftHandle"父组件自定义方法
   /> -->
  <div :class="fixed ? 'fixed' : ''">
    <div class="navbar" ref="navbar" :style="{'color':color}">
      <div class="navbar-left" v-show="!leftIcon">
        <i class="iconfont icon-fanhui" @click="onLeftHandle"></i>
      </div>
      <div class="navbar-text">
        {{title ? title : '标题栏'}}
      </div>
      <slot name="nav-right"></slot>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    title:{
      type:String,
    },
    fixed:{
      type:Boolean,
      default:() => {
        return false
      }
    },
    leftIcon: {
      type: Boolean,
      default:() => {
        return false
      } 
    },
    color: {
      type: String
    },
    toTop: {
      type: String,
      default: () => {
        return '30'
      }
    },
    endTop: {
      type: String,
      default: () => {
        return '300'
      }
    },
    changeColor: {
      type: String
    }
  },
  mounted () {
    this.watchTop ()
  },
  methods: {
        
    // 当点击子组件的按钮的时候，如何 拿到 父组件传递过来的 func 方法，并调用这个方法？？？
    onLeftHandle () {
      this.$emit('click-left')
    },
     //滚动监听，然后让top栏背景变白
    watchTop () {
      //toTop开始变化的位置，endTop结束的透明渐变的位置
      let {toTop, endTop, changeColor} = this
      let navbar = this.$refs.navbar
      let navbarText = navbar.getElementsByClassName('navbar-text') 
      let leftIcon = navbar.getElementsByClassName('icon-fanhui') 
      window.addEventListener('scroll',()=>{
        this.offsetTop=window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        // console.log(this.offsetTop);
        if (this.offsetTop>toTop) {
          let a = this.offsetTop/(endTop-toTop)
          navbar.style.backgroundColor='rgba(255,255,255,'+a+')'
          navbar.style.color=(changeColor ? changeColor : '#333333')
        }else{
          navbar.setAttribute("style","background:linear-gradient(top,#000,#fff)")
        }
      },true)
    }
  }
}
</script>
<style scoped>
.fixed {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 3;
}
.fixed .navbar {
  height: 46px;
  border-bottom:1px solid #cccccc ;
  line-height: 46px;
  text-align: center;
  position: relative;
}
.navbar .navbar-left {
  position: absolute;
  top: 0;
  bottom: 0;
  padding: 0 16px;
}
.navbar .icon-fanhui {
  margin-right: 4px;
  font-size: 16px;
}
.navbar .navbar-text {
  font-size: 16px;
  max-width: 60%;
  margin: 0 auto;
  font-weight: 500;
}
</style>